#include <string.h>
#include "DialogueManager.h"
#include "FileReader.h"
#include "include.h"

DialogueManager::DialogueManager()
{
	hasSpoken = false;
	conversationList = NULL;
	lastConversation = NULL;
	firstConversationConditional = NULL;
	
}
DialogueManager::DialogueManager(char * fileName)
{
	hasSpoken = false;
	conversationList = NULL;
	lastConversation = NULL;
	firstConversationConditional = NULL;
	LoadDialogueFile(fileName);
}
void DialogueManager::LoadDialogueFile(char * fileName)
{
	FILE * fptr = NULL;
	if((fptr = fopen(fileName, "r")) == NULL)
	{
		printf("Error opening Dialogue -%s-\n", fileName);
	}
	
	char * tag;
	while((tag = FileReader::GetNextTag(fptr)) != NULL)
	{
		printf("TAG: %s\n", tag);
		//read through the tag, one element at a time
		int pos = 0;		
		char * element = FileReader::GetNextElement(tag, &pos);
		
		printf("ELEMENT: %s\n", element);
		
		switch(GetElementType(element))
		{
			case FIRST_CONDITIONAL_TYPE: 
				HandleFirstConditionalTag(tag,pos);
				break;
			case CONVERSATION_TYPE:
				HandleConversationTag(tag,pos);
				break;
		}
		if(element != NULL)
			free(element);
		element = NULL;
		if(tag != NULL)
			free(tag);
		tag = NULL;
	}
	fclose(fptr);

}
int DialogueManager::GetElementType(char * element)
{
	if(strcmp(element,"firstConditional") == 0)
		return FIRST_CONDITIONAL_TYPE;
	if(strcmp(element,"conversation") == 0)
		return CONVERSATION_TYPE;
	return UNKNOWN_TYPE;
}
void DialogueManager::HandleFirstConditionalTag(char * tag, int pos)
{
	firstConversationConditional = FileReader::ReadNextConditionalStatement(tag, &pos);
}
void DialogueManager::HandleConversationTag(char * tag, int pos)
{
	char * key = FileReader::ReadNextString(tag, &pos);
	char * text = FileReader::ReadNextString(tag, &pos);
	ConditionalStatement * nextConditional = FileReader::ReadNextConditionalStatement(tag, &pos);
	
	Conversation * conversation = new Conversation(text, nextConditional);
	if(conversationList)
	{
		conversationList->Add(key, conversation);
	}
	else
	{
		conversationList = new KeyedList<Conversation>(key, conversation);
	}
}
char * DialogueManager::Speak(Dictionary * dictionary)
{
	if(!hasSpoken)
	{
		char * key = firstConversationConditional->Evaluate(dictionary);	
		if(!key)
		{
			return NULL;
		}
		Conversation * nextConversation = conversationList->GetValue(key);
		if(!nextConversation)
		{
			return NULL;
		}
		lastConversation = nextConversation;
		hasSpoken = true;
		return nextConversation->GetText();
	}
	else if(lastConversation)
	{
		char * key = lastConversation->NextConversationKey(dictionary);	
		if(!key)
		{
			return NULL;
		}
		Conversation * nextConversation = conversationList->GetValue(key);
		if(!nextConversation)
		{
			return NULL;
		}
		lastConversation = nextConversation;
		return nextConversation->GetText();
	}
	return NULL;
}
